﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace IronSuit.DataMap
{
	public class SqlCreator
	{
		public List<string> FieldList = new List<string>();
		public List<string> OrderList = new List<string>();
		public List<SqlParameter> ParameterList = new List<SqlParameter>();
		public string Condition;
		public string KeyField;
		public string TableName;
		public int PageNo = 1;
		public int PageSize = 20;
		public QueryTypeOption QueryType = QueryTypeOption.Nomal;

		public string GetSql()
		{
			string OrderStr="";
			if (OrderList.Count > 0)
				OrderStr = " order by " + string.Join(",", OrderList.ToArray());
			else if (!string.IsNullOrEmpty(KeyField))
				OrderStr = " order by " + KeyField;
			StringBuilder SB = new StringBuilder();
			if (PageNo == 1)
			{
				SB.Append("select top " + PageSize.ToString() + " " + string.Join(",", FieldList.ToArray()));
				SB.Append(" from " + TableName + " where " + Condition + OrderStr);
			}
			else
			{
				SB.Append("select top " + PageSize.ToString() + " " + string.Join(",", FieldList.ToArray()));
				SB.Append(" from " + TableName + " where " + Condition );
				SB.Append(" and "+KeyField +" not in (");
				SB.Append("select top " + ((PageNo-1) * PageSize).ToString() + " " + string.Join(",", FieldList.ToArray()));
				SB.Append(" from " + TableName + " where " + Condition);
				SB.Append(OrderStr);
				SB.Append(")");
				SB.Append(OrderStr);
			}
			return SB.ToString();
		}
	}
	public enum QueryTypeOption
	{
		Nomal,
		Distinct,
		Group
	}
}
